import json
import os
import threading
import time

from flask import Flask, request

from PedestrianDet.cfg_PD import save_path
from PedestrianDet.logger_PD import logger
from PedestrianDet.utils_PD import download, detect_body_parts

logger.info('AppPedestrian starts')
app = Flask(__name__)


@app.route('/imr-ai-service/pedestrian/check/<file_id>', methods=['POST'])
def check(file_id):
    if request.method == "POST":
        file_id = file_id.replace("\n", "")
        c_da = request.data
        data = json.loads(c_da.decode())
        recode_id = data['recodeId']
        equipment_id = data['equipmentId']
        time_take = time.time()
        print('下载文件', file_id)
        file_name = download(req_id=file_id, from_temp=True)
        print('下载结果:', file_name)
        if not (file_name.endswith('.jpg') or file_name.endswith('.png')):
            result = file_name
            ret = False
        else:
            t_ped = threading.Thread(
                target=detect_body_parts,
                args=(
                    file_id,
                    file_name,
                    recode_id,
                    equipment_id
                )
            )
            t_ped.start()
            result = '异步处理（回调）模式'
            ret = True
        time_take = time.time() - time_take
        msg = {True: '成功', False: '失败'}
        return json.dumps(
            {
                'ret': ret,
                'msg': msg[ret],
                'data': result,
                'timeTake': round(time_take, 4)
            },
            ensure_ascii=False
        )


if __name__ == '__main__':
    pid = os.getpid()
    print('pid is:', pid)
    with open(os.path.join(save_path, 'app_pid.txt'), 'w') as f:
        f.writelines([str(pid)])
    app.run(
        host="0.0.0.0",
        port=int("20294"),
        debug=False, threaded=True)
